from django import forms
from django.contrib.auth import get_user_model
from .models import CaptchaModel

User = get_user_model()

class RegisterForm(forms.Form):
    username = forms.CharField(max_length=20, min_length=1, error_messages={
        'max_length': '用户名长度在1-20之间！',
        'min_length': '用户名长度在1-20之间！',
    })
    email = forms.EmailField(error_messages={
        'invalid': '请输入正确的邮箱！',
    })
    captcha =forms.CharField(max_length=4, min_length=4)
    password = forms.CharField(max_length=20, min_length=4, error_messages={
        'max_length': '密码长度在4-20之间！',
        'min_length': '密码长度在4-20之间！',
    })

    #验证邮箱是否存在
    def clean_email(self):
        email = self.cleaned_data.get('email')
        exists = User.objects.filter(email=email).exists()
        if exists:
            raise forms.ValidationError('邮箱已经被注册！')
        return email

    #验证 验证码是否匹配
    def clean_captcha(self):
        captcha = self.cleaned_data.get('captcha')
        email = self.cleaned_data.get('email')
        captcha_model = CaptchaModel.objects.filter(email=email, captcha=captcha).first()
        if not captcha_model:
            raise forms.ValidationError('验证码和邮箱不匹配！')
        captcha_model.delete()
        return captcha

class LoginForm(forms.Form):
    email = forms.EmailField(error_messages={'invalid': '请传入一个正确的邮箱！'})
    password = forms.CharField(max_length=20, min_length=6)
    remember = forms.IntegerField(required=False)

    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')
        user = User.objects.filter(email=email).first()
        if user and user.check_password(password):
            return cleaned_data
        raise forms.ValidationError('邮箱与密码不匹配！')





